<template>
  <div class="good-detail">
    <div v-if="loading">加载中...</div>
    <div v-else>
      <h1>{{ good.title }}</h1>
      <p class="description">{{ good.description }}</p>
      <p v-if="good.type === 1" class="type-sell">出售</p>
      <p v-else-if="good.type === 2" class="type-rent">租赁</p>
      <p v-if="good.type === 1" class="price">租金: {{ good.price }} 元/天（共 {{ good.rentDay }} 天）</p>
      <p v-else-if="good.type === 2" class="price">出售价格: {{ good.price }} 元</p>
      <p class="like-count">点赞数: {{ good.likeCount }}</p>

      <!-- 图片展示区域 -->
      <div class="image-container">
        <img
            v-for="(imageUrl, index) in good.imageUrls"
            :key="index"
            :src="imageUrl"
            alt="商品图片"
            class="goods-image"
        >
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      good: {}, // 商品详情
      loading: false
    };
  },
  created() {
    this.fetchGoodDetail();
  },
  methods: {
    async fetchGoodDetail() {
      this.loading = true;
      try {
        const goodId = this.$route.params.id;
        const response = await axios.get(`http://localhost:9090/good/detail`, {
          params: { id: goodId }
        });
        // 直接使用 imageUrls 字段，不再处理 images 字段
        this.good = {
          ...response.data.data,
          // 如果后端返回的 imageUrls 是字符串格式，可以在此转换为数组
          imageUrls: Array.isArray(response.data.data.imageUrls)
              ? response.data.data.imageUrls
              : JSON.parse(response.data.data.imageUrls || '[]')
        };
      } catch (error) {
        console.error('获取商品详情失败:', error);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.good-detail {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

h1 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #333;
}

.description {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.6;
}

.type-sell {
  color: #07c160;
  font-weight: 600;
  margin: 10px 0;
}

.type-rent {
  color: #1989fa;
  font-weight: 600;
  margin: 10px 0;
}

.price {
  font-size: 18px;
  color: #ff6b6b;
  margin: 12px 0;
}

.like-count {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

/* 图片容器样式 */
.image-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.goods-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.goods-image:hover {
  transform: scale(1.02);
}

/* 响应式适配 */
@media (max-width: 600px) {
  .image-container {
    grid-template-columns: 1fr;
  }

  .goods-image {
    height: 240px;
  }
}
</style>